package homework;

import java.util.PriorityQueue;

//模拟实现定时器

class MyTimerTask implements Comparable<MyTimerTask>{
    private Runnable task;
    private long time;

    public MyTimerTask(Runnable task,long delay){
        this.task = task;
        this.time = System.currentTimeMillis() + delay;
    }

    public Runnable getTask(){
        return task;
    }

    public long getTime(){
        return time;
    }

    @Override
    public int compareTo(MyTimerTask o) {
        return (int) (this.time - o.time);
    }
}

class MyTimer{
    private PriorityQueue<MyTimerTask> queue = new PriorityQueue<MyTimerTask>();
    private Object locker = new Object();

    public MyTimer(){
        Thread t = new Thread(()->{
            while (true) {
                try {
                    synchronized(locker){
                        if (queue.isEmpty()) {
                            locker.wait();
                        }
                        MyTimerTask task = queue.peek();
                        long curTime = System.currentTimeMillis();
                        if (curTime < task.getTime()) {
                            locker.wait(task.getTime() - curTime);
                        }else{
                            task.getTask().run();
                            queue.poll();
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        t.start();
    }
}


public class demo10 {

}
